//
//  SWSearchTableViewController.m
//  sc-cyan-ios
//
//  Created by lvjian01 on 2017/12/16.
//  Copyright © 2017年 greenbuilding. All rights reserved.
//

#define searchSectionTitlekey @"title"
#define searchListKey @"searchList"

#import "SWSearchTableViewController.h"
#import "UIBarButtonItem+SWBarButtobItem.h"
#import "SWSearchTableViewTagCell.h"
#import "SWSearchTableViewNoDataCell.h"
#import "SWSearchTableViewProductCell.h"
#import "SWSearchTableViewLessingCompanyCell.h"
#import "SWSearchTableViewInquiryCell.h"
#import "SWSearchNaviView.h"



@interface SWSearchTableViewController ()

//@property (nonatomic, strong) UIView *searchNaviView;
@property (nonatomic, strong) SWSearchNaviView *searchNaviView;

@property (nonatomic, strong) NSMutableArray *searchList;
@property (nonatomic) BOOL isFirstShow;//是否是第一次显示该页面，需要显示历史搜索和热门搜索


@end

@implementation SWSearchTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.estimatedRowHeight = 100;  //  随便设个不那么离谱的值
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([SWSearchTableViewProductCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:NSStringFromClass([SWSearchTableViewProductCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([SWSearchTableViewLessingCompanyCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:NSStringFromClass([SWSearchTableViewLessingCompanyCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([SWSearchTableViewInquiryCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:NSStringFromClass([SWSearchTableViewInquiryCell class])];
    
    self.isFirstShow = YES;
//    self.searchList = [NSMutableArray arrayWithArray:@[
//  @{@"title":@"历史搜索",@"searchList":@[@"hehe",@"hengheng",@"haha",@"qnmlgb",@"这是什么鬼",@"younimameifangjia",@"zhenshiriligoule"]}
//  ,@{@"title":@"热门搜索",@"searchList":@[@"sousuonimeia",@"he",@"tashisdfas",@"ajlksdj"]}
//  ,@{@"title":@"租赁企业"}
//  ]];
    self.searchList = [NSMutableArray arrayWithArray:@[
                                                       @{@"title":@"历史搜索",@"searchList":@[@"asdfsadf",@"2343sdf",@"asdfas"]}
                                                       ,@{@"title":@"热门搜索",@"searchList":@[@"asdfs",@"asdfasd",@"asdfs"]}
                                                       ,@{@"title":@"租赁企业"}
                                                       ]];
    [self.tableView reloadData];

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar addSubview:self.searchNaviView];
    
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.searchNaviView removeFromSuperview];
    
}

- (SWSearchNaviView *)searchNaviView{
    if (!_searchNaviView) {
        _searchNaviView = [[SWSearchNaviView alloc] initWithFrame:self.navigationController.navigationBar.bounds];
        MJWeakSelf
        _searchNaviView.popViewBack = ^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        };
        _searchNaviView.searchText = ^(NSString *text) {
//            这里进行搜索操作
            [weakSelf searchText:text];
        };
        
        
    }
    
    return _searchNaviView;
}

- (void)searchTextField{
    NSLog(@"这里是搜索功能");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma 搜索操作，搜索后进入搜索页
- (void)searchText:(NSString *)text{
    self.isFirstShow = NO;
    
    
//    self.searchList = ......
    
    
    [self.tableView reloadData];
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
//    if (self.isFirstShow) {
//        return 2;
//    }
//    return 3;
    
    return self.searchList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *searchList = [[self.searchList objectAtIndex:section] objectForKey:searchListKey];

    if (self.isFirstShow) {
        return 1;
    }
    
    if (!searchList || searchList.count == 0) {
        return 1;
    }
    return searchList.count;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    
//    NSArray *searchList = [[self.searchList objectAtIndex:indexPath.section] objectForKey:searchListKey];
//
//    
//    if (searchList && searchList.count != 0) {
//        switch (indexPath.section) {
//            case SWSearchNoDataTypeProduct:
//                return 94;
//            case SWSearchNoDataTypeCompany:
//                return 79;
//            case SWSearchNoDataTypeInquiry:
//                return 94;
//            default:
//                break;
//        }
//    }
//    
////    return [super tableView:tableView heightForRowAtIndexPath:indexPath];
//    return UITableViewAutomaticDimension;
//}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSArray *searchList = [[self.searchList objectAtIndex:indexPath.section] objectForKey:searchListKey];

    if (self.isFirstShow) {
        SWSearchTableViewTagCell *tagCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SWSearchTableViewTagCell class]) forIndexPath:indexPath];
        tagCell.titleArray = searchList;
        
        MJWeakSelf
        tagCell.selectedItemWithTitle = ^(NSString *title) {
//            这里执行搜索关键词的动作
            [weakSelf searchText:title];
        };
        
//        tagCell.heightUpdated = ^(CGFloat height) {
//            [self.tableView reloadData];
//        };
        
        return tagCell;
    }
    
    if (!searchList || searchList.count == 0) {
        SWSearchTableViewNoDataCell *noDataCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SWSearchTableViewNoDataCell class]) forIndexPath:indexPath];
        
        noDataCell.nodataType = indexPath.section;
        
        noDataCell.postMoreInfo = ^(SWSearchNoDataType nodataType) {
            
            NSLog(@"点击发布按钮，跳转到发布页面");
            
        };
        
        return noDataCell;
    }
    
    switch (indexPath.section) {
        case SWSearchNoDataTypeProduct:
        {
            SWSearchTableViewProductCell *productCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SWSearchTableViewProductCell class]) forIndexPath:indexPath];
            
//            传值
//            productCell.
            
            return productCell;
        }
        case SWSearchNoDataTypeInquiry:
        {
            SWSearchTableViewInquiryCell *inquiryCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SWSearchTableViewInquiryCell class]) forIndexPath:indexPath];
            
//            传值
//            inquiryCell.
            
            return inquiryCell;
        }
        case SWSearchNoDataTypeCompany:
        {
            SWSearchTableViewLessingCompanyCell *companyCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SWSearchTableViewLessingCompanyCell class]) forIndexPath:indexPath];
//            传值
//            companyCell.
            
            return companyCell;
        }
        default:
            break;
    }
    
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSArray *searchList = [[self.searchList objectAtIndex:indexPath.section] objectForKey:searchListKey];
    
    if (self.isFirstShow || !searchList || searchList.count == 0) {
        return;
    }
    
//    进入详情页
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0001;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    NSArray *searchList = [[self.searchList objectAtIndex:section] objectForKey:searchListKey];
    NSString *headerTitle = [[self.searchList objectAtIndex:section] objectForKey:searchSectionTitlekey];

    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Main_Screen_Width, tableView.sectionHeaderHeight)];
    headerView.backgroundColor = [UIColor gb_background_f6f6f6];
    
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, Main_Screen_Width - 40, tableView.sectionHeaderHeight)];
    headerLabel.text = headerTitle;
    headerLabel.font = SYSTEMFONT(12);
    headerLabel.textColor = [UIColor gb_textColor_999999];
    [headerView addSubview:headerLabel];
    
    UIButton *headerDetailButton = [[UIButton alloc] initWithFrame:CGRectMake(Main_Screen_Width - 40, 2, 40, tableView.sectionHeaderHeight - 4)];
    [headerDetailButton setTitle:@"" forState:UIControlStateNormal];
//    headerDetailButton.backgroundColor = [UIColor redColor];
    [headerDetailButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    headerDetailButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
    headerDetailButton.tag = section;
    [headerDetailButton addTarget:self action:@selector(sectionDetailButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
    headerDetailButton.hidden = YES;
    [headerView addSubview:headerDetailButton];
    
    if (self.isFirstShow && section == 0) {
        headerDetailButton.hidden = NO;
        [headerDetailButton setImage:[UIImage sw_debugImage] forState:UIControlStateNormal];
    }
    
//    if (!self.isFirstShow)//只要不是第一次，
//    不是第一次并且有数据
    if (!self.isFirstShow && searchList && searchList.count != 0) {
        headerDetailButton.hidden = NO;
        [headerDetailButton setTitle:@"更多" forState:UIControlStateNormal];
        [headerDetailButton setTitleColor:[UIColor gb_textColor_999999] forState:UIControlStateNormal];
        [headerDetailButton.titleLabel setFont:SYSTEMFONT(12)];
    }
    
//    headerView.backgroundColor = [UIColor lightGrayColor];
    
    return headerView;
}

- (void)sectionDetailButtonTouched:(UIButton *)button{
    
    NSInteger section = button.tag;
    
    if (self.isFirstShow) {
        NSLog(@"清除历史搜索");
        return;
    }
    
    switch (section) {
        case SWSearchNoDataTypeProduct:{
            NSLog(@"更多租赁产品");
            SWProductListViewController *productVC = [SWProductListViewController dd_instanceFromStoryboard];
            [self.navigationController showViewController:productVC sender:nil];
        }
            break;
        case SWSearchNoDataTypeInquiry:{
            NSLog(@"更多求租信息");
            SWInquiryListViewController *inquiryVC = [SWInquiryListViewController dd_instanceFromStoryboard];
            [self.navigationController showViewController:inquiryVC sender:nil];
        }
            break;
        case SWSearchNoDataTypeCompany:{
            NSLog(@"更多租赁企业");
            SWCompanyListViewController *companyVC = [SWCompanyListViewController dd_instanceFromStoryboard];
            [self.navigationController showViewController:companyVC sender:nil];
        }
            break;
        default:
            break;
    }
}




/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
